package com.topisv.tms.web.work;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.ExpressStyle;
import com.topisv.tms.entity.LogisticsCompany;
import com.topisv.tms.entity.PackformStyle;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.repository.work.WorkOrderDao;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.ExpressStyleService;
import com.topisv.tms.service.LogisticsCompanyService;
import com.topisv.tms.service.PackformStyleService;
import com.topisv.tms.service.PrintStyleService;
import com.topisv.tms.service.UserService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.vo.PrinterStyleType;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.utils.http.SynchroShippedBatchQueue;
import com.topisv.tms.utils.print.PickPrintUtil;
import com.topisv.tms.utils.vo.WMSPrinter;

import net.sf.json.JSONObject;

/**
 * 打印任务_control
 * @author ch
 */
@Controller
@RequestMapping({ "/print" })
public class PrintController {

	private static final Logger logger = LoggerFactory.getLogger(PrintController.class);

	@Autowired
	private WorkTaskService workTaskService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private PackformStyleService packformStyleService;
	@Autowired
	private ExpressStyleService expressStyleService;
	@Autowired
	private PickPrintUtil pickPrintUtil;
	@Autowired
	private LogisticsCompanyService logisticsCompanyService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private WorkOrderDao workOrderDao ;
	@Autowired
	private EdiOrderService ediOrderService ;
	@Autowired
	private UserService userService ;
	@Autowired
	private PrintStyleService printStyleService;
	

	/**
	 * 导向打印订单页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "v2_toPrintPage")
	public String toPrintPage(ServletRequest request,HttpServletResponse response,Model model) throws Exception{

		//查出当前用户关联的商家列表
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
		model.addAttribute("customerList",customerList);
		model.addAttribute("userType",curUser.userType);
		
		//快递公司
		List<LogisticsCompany> cmpList=this.logisticsCompanyService.findAll();
		model.addAttribute("cmpList",cmpList);
		
	    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	    Calendar cal=Calendar.getInstance();
	    cal.setTime(new Date()); 
	    Date fromDate=sdf.parse(sdf.format(new Date())+" 00:00:00");
		cal.add(Calendar.DATE, 1);
		Date toDate=sdf.parse(sdf.format(cal.getTime())+" 23:59:59");
		//如果是paiu用户,初始化数据
		if("paiu".equals(curUser.userType)){
			Map<String, Object> param=new HashMap<String, Object>();
			param.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
			param.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
		    param.put("printStatus", "unprinted");
		    param.put("flowType", "prePrint");
		    param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			param.put("num", 50);
			List<WorkTask> taskList=this.workTaskService.loadTaskByParam(param);
			model.addAttribute("taskList",taskList);
			model.addAttribute("_printStatus","unprinted");
			model.addAttribute("_num",50);
		}
		
		//如果是商家用户，加载数据
		if("customer".equals(curUser.userType)){
			
			Map<String, Object> param=new HashMap<String, Object>();
			String customerCode=curUser.customerCode;
			param.put("customerCodes", customerCode);
		    param.put("flowType", "prePrint");
		    param.put("printStatus", "unprinted");
		    param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			param.put("num", 50);
			List<WorkTask> taskList=this.workTaskService.loadTaskByParam(param);
		    model.addAttribute("taskList",taskList);
		    model.addAttribute("_printStatus","unprinted");
		    model.addAttribute("_customerCode",customerCode);
		    
		    List<PackformStyle> packformStyles=packformStyleService.findByCustomerCode(customerCode);//根据商家编码获取发货单
		    List<ExpressStyle> expressStyles=expressStyleService.findByStyleDufault(customerCode);//根基商家编码获取快递单模版
		    model.addAttribute("packformStyles",packformStyles);
		    model.addAttribute("expressStyles",expressStyles);
			
			//初始化仓库数据
			List<AreaGroup> wmList=this.areaGroupService.loadByCustomerCodeAndPaiu(customerCode);
			model.addAttribute("wmList", wmList); 
			model.addAttribute("_num",50);
		}
	    
		return "work/print/printList";
	}
	
	/**
	 * 查询打印任务
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "v2_queryPrintList")
	public String queryPrintList(Model model, ServletRequest request, ServletResponse response) throws Exception {
		try {
				//查出当前用户关联的商家列表
				ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
				List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
				model.addAttribute("customerList",customerList);
				model.addAttribute("userType",curUser.userType);
				
				//快递公司
				List<LogisticsCompany> cmpList=this.logisticsCompanyService.findAll();
				model.addAttribute("cmpList",cmpList);
			    
			    //查询打印任务
				Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
				String customerCode=(String)param.get("customerCode");
				String warehouseCode=(String)param.get("warehouseCode");
				String fromDateStr=(String) param.get("fromDate");
				String toDateStr=(String) param.get("toDate");
				String printStatus=(String) param.get("printStatus");
				String createName=(String)param.get("createName");
				String psFlag = (String)param.get("psFlag");//优先派送标志
				
				String num =(String)param.get("num");
				
				
				Customers customers=this.customersService.findByCustomerCode(customerCode);
				model.addAttribute("customers",customers);
				
				String taskCode=(String) param.get("taskCode");
				//按订单查询显示
				String orderno=(String) param.get("orderno");
				if(StringUtils.isNotBlank(orderno)){
				  WorkOrder order=this.workOrderService.loadByOrdernoOrCustomerorderno(orderno);
				  model.addAttribute("flag","order");
				  if(order!=null){
					  model.addAttribute("order",order);
				  }
				// 按任务号查询
				} else if(StringUtils.isNotBlank(taskCode)){
					List<WorkTask> workTaskList=this.workTaskService.loadTaskByTaskCode(taskCode);
					if(workTaskList.size()>0){
					    model.addAttribute("taskList",workTaskList);
					    model.addAttribute("_taskCode", taskCode);
					}
				//按任务列表显示	
				}else{
					model.addAttribute("flag","task");
					if(StringUtils.isBlank(customerCode)){
						String customerCodes=this.customersService.loadCustomerByAuthority(curUser.jobuuid);
						param.put("customerCodes", StringUtils.isBlank(customerCodes)?"blank":customerCodes);
					}else{
						param.put("customerCodes", customerCode);
					}
					
					if(StringUtils.isBlank(warehouseCode)){
						param.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
					}else{
						param.put("areagroups", warehouseCode);
					}
					
					// begin 增加创建者查询条件 By rongfei.zhang
					if(StringUtils.isNotBlank(createName)){
						List<User> creatorList = userService.findByRealname(createName);
						if(creatorList != null && creatorList.size() > 0){
							List<String> createIdList = new ArrayList<String>();
							for(User creator : creatorList){
								createIdList.add(creator.getId().toString());
							}						
							param.put("createrIds", StringUtils.join(createIdList, ":"));
						}else{
							param.put("createrIds", "-1");
						}
					}
					// end 增加创建者查询条件 By rongfei.zhang
					if(StringUtils.isNotBlank(num)){
						 param.put("num",num);
					}else {
						 param.put("num",50);
					}
					Date fromDate=null;
					Date toDate=null;
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					
					if(StringUtils.isNotEmpty(fromDateStr)){
						fromDate=sdf.parse(fromDateStr+" 00:00:00");
					}
					if(StringUtils.isNotEmpty(toDateStr)){
						toDate=sdf.parse(toDateStr+" 23:59:59");
					}
					param.put("fromDate", fromDate);
					param.put("toDate", toDate);
				    param.put("flowType", "prePrint");
					
				   
				    
					List<WorkTask> taskList=this.workTaskService.loadTaskByParam(param);
				    model.addAttribute("taskList",taskList);
				    model.addAttribute("_customerCode", customerCode);
				    model.addAttribute("_warehouseCode", warehouseCode);
				    model.addAttribute("_printStatus",printStatus);
				    model.addAttribute("_createName",createName);
				    model.addAttribute("_psFlag",psFlag);
				    
				    model.addAttribute("_num",num);
				    
				    List<PackformStyle> packformStyles=packformStyleService.findByCustomerCode(customerCode);//根据商家编码获取发货单
				    List<ExpressStyle> expressStyles=expressStyleService.findByStyleDufault(customerCode);//根基商家编码获取快递单模版
				    model.addAttribute("packformStyles",packformStyles);
				    model.addAttribute("expressStyles",expressStyles);
					
					
				}
				
				
			    
			    //初始化仓库数据
			    if(StringUtils.isNotBlank(customerCode)){
			    	List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
					model.addAttribute("warehouseList", warehouseList);
			    }
		    
			} catch (Exception e) {
				
				logger.error("error",e);
			}

		return "work/print/printList";
	}
	
	
	
	/**
	 * 导向重新打印页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toReprintPage/{taskCode}", method = RequestMethod.GET)
	public String toReprintPage(@PathVariable("taskCode") String taskCode, Model model) {
		try {

			 Map<String, Object> param=new HashMap<String, Object>();
			 param.put("taskCode", taskCode);
			 WorkTask workTask=this.workTaskService.loadTaskByCode(taskCode);
			 List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
			 model.addAttribute("orderList",orderList);
			 List<PackformStyle> packformStyles=packformStyleService.findByCustomerCode(workTask.getCustomerCode());//根据商家编码获取发货单
			 List<ExpressStyle> expressStyles=null;
//			 if(StringUtils.isNotBlank(workTask.getCompanyCode())){
//				 expressStyles=this.expressStyleService.findStyle(workTask.getCompanyCode(), workTask.getCustomerCode(), workTask.getWarehouseCode());
//			 }else{
//				 expressStyles=this.expressStyleService.findByCustomerCodeAndAreaGroupCode(workTask.getCustomerCode(), workTask.getWarehouseCode());//根基商家编码获取快递单模版
//			 }
			 model.addAttribute("workTask",workTask);
			 model.addAttribute("packformStyles",packformStyles);
			 model.addAttribute("expressStyles",expressStyles);
			 model.addAttribute("taskCode",taskCode);
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/print/reprint";
	}
	
	/**
	 * 验证快递单号
	 * @param taskCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxVerifyExpress", method = RequestMethod.POST)
	public void ajaxVerifyExpress(
			@RequestParam(value = "taskCode") String taskCode,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			logger.info("开始验证快递单号:"+taskCode);
			json=new JSONObject();
			out=response.getWriter();
			List<WorkOrder> workOrders=this.workOrderService.findByTaskCode(taskCode);
			json.put("status", "1");
			json.put("content", workOrders);
			out.print(json.toString());
			logger.info(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
	}
	
	
	
	@RequestMapping(value = "ajaxSuccedOrdenos", method = RequestMethod.POST)
	public void ajaxSuccedOrdenos(
			@RequestParam(value = "ordenos") String ordenos,
			HttpServletResponse response) {
		
			logger.info("发送指令成功的订单号==="+ordenos);
	}
	
	/**
	 * 
	 * 检验该商家是否需要打印随箱单
	 *
	 * @param workIds
	 * @param number
	 * @param response [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "checkCustomerPackFormStatus", method = RequestMethod.POST)
	public void checkCustomerPackFormStatus(@RequestParam(value = "customerCode") String customerCode, HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;

		try {
			json = new JSONObject();
			out = response.getWriter();
			
			Customers customers = customersService.findByCustomerCode(customerCode);
			if ("1".equals(customers.getPackStatus())){
				json.put("status", "1");
			}else{
				json.put("status", "0");
				json.put("content", "该商家不需要打随箱单");
			}
			
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			logger.error("打印加载错误", e);
		} finally {
			
			out.print(json.toString());
		}
	}
	
	/**
     * 统计随箱单打印AJAX次数
     * @param workIds
     * @param number
     * @param response
     */
	@RequestMapping(value = "ajaxPackFormCount", method = RequestMethod.POST)
	public void ajaxPackFormCount(
			@RequestParam(value = "workIds") String workIds,
			@RequestParam(value = "number") int number,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			logger.info("开始随箱单的AJAX分页显示打印");
			logger.info("workIds==="+workIds+"\tnumber="+number);
			json=new JSONObject();
			out=response.getWriter();
			String content=pickPrintUtil.packFormCount(workIds, number);
			json.put("status", "1");
			json.put("content", content);
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
		logger.info(json.toString());
	}
	
	/**
	 * 修改流水批次的随箱单打印状态
	 * @param workIds
	 * @param response
	 */
	@RequestMapping(value = "ajaxWorkTaskPackFormStatus", method = RequestMethod.POST)
	public void ajaxWorkTaskPackFormStatus(
			@RequestParam(value = "workIds") String workIds,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			logger.info("开始修改随箱单的状态==workIds==="+workIds);
			json=new JSONObject();
			out=response.getWriter();
			workTaskService.updatePackFormStatus(workIds);
			json.put("status", "1");
			json.put("content", "修改成功");
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("加载错误", e);
		}
		logger.info(json.toString());
	}
	
	/**
	 * 修改流水批次的随箱单打印状态
	 * @param workIds
	 * @param response
	 */
	@RequestMapping(value = "ajaxWorkTaskPrintStatus", method = RequestMethod.POST)
	public void ajaxWorkTaskPrintStatus(
			@RequestParam(value = "taskCode") String taskCode,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			logger.info("开始修改随箱单状态==taskCode==="+taskCode);
			json=new JSONObject();
			out=response.getWriter();
			WorkTask workTask=this.workTaskService.loadTaskByCode(taskCode);
			if(workTask==null){
				json.put("status", "0");
				json.put("content", "该拣货任务号不存在");
				out.print(json.toString());
				return;
			}
			this.workTaskService.setPrintStatus(workTask);
			json.put("status", "1");
			json.put("content", workTask);
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("加载错误", e);
		}
		logger.info(json.toString());
	}
	
	/**
	 * 根据流水批次号批量随箱单打印
	 * @param workNos
	 * @param number
	 * @param ordeno
	 * @param response
	 */
	@RequestMapping(value = "ajaxPrintPackForm", method = RequestMethod.POST)
	public void ajaxPrintPackForm(
			@RequestParam(value = "workIds") String workIds,
			@RequestParam(value = "number") int number,
			@RequestParam(value = "nextOrdeno") String ordeno,
			@RequestParam(value = "packformStyleId") Long packformStyleId,
			@RequestParam(value = "printName") String printName,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		StringBuffer sb=new StringBuffer();
		String index="pending";//打印完毕标记处
		try {
			logger.info("ajaxPrintPackFormworkIds==="+workIds+"\tnumber="+number+"\tordeno="+ordeno+"\tpackformStyleId="+packformStyleId);
			json=new JSONObject();
			out=response.getWriter();
			List<PrinterStyleType> printerStyleTypes=pickPrintUtil.printPackForm(workIds, ordeno, number, packformStyleId,sb);
			index=sb.toString();
			
			if("finish".equals(index)) updatePickFormTimes(workIds);
			json.put("status", "1");
			json.put("content", printerStyleTypes);
			json.put("index", index);
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
	}

	/**
	 * 修改打印次数
	 * 
	 * @param workIds
	 *            任务号组和 每个任务ID以“：”分开
	 */
	private void updatePickFormTimes(String workIds) {
		logger.info("修改随箱单打印次数workIds==="+workIds);
		String[] ids = workIds.split(":");
		List<String> taskCodes = new ArrayList<String>();
		for (String id : ids) {
			WorkTask workTask = workTaskService
					.loadTaskById(Long.parseLong(id));
			taskCodes.add(workTask.getTaskCode());
		}
		
		//修改随箱单的打印状态 bug554 by zhangweize 2016-10-31 
		workTaskService.updatePackFormStatus(workIds);
		
		workOrderService.updatePrintFormFlagByTaskCodes(taskCodes);
		// for(String taskCode:taskCodes){
		// workOrderService.updatePrintFormFlagByTaskCode(taskCode);
		// }
	}
	
	/**
	 * 根据订单号打印随箱单
	 * @param ordenos
	 * @param packformStyleId
	 * @param response
	 */
	@RequestMapping(value = "ajaxPrintPackFormOrdenosNew", method = RequestMethod.POST)
	public void ajaxPrintPackFormOrdenosNew(
			@RequestParam(value = "ordenos") String ordenos,
			@RequestParam(value = "packformStyleId") Long packformStyleId,
			@RequestParam(value = "workTaskId") String workTaskId,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			logger.info("ajaxPrintPackFormOrdenosNew打印的订单号:"+ordenos+"---随箱单ID:"+packformStyleId);
			json=new JSONObject();
			out=response.getWriter();
			
			//获取随箱单样式
			List<PrinterStyleType> printerStyleTypes=pickPrintUtil.printPackForm(ordenos, packformStyleId);
			
			//add 任务打印完但是状态还是未打印 bug411 by zhangweize
			workTaskService.updatePackFormStatus(workTaskId);
			
			//修改打印次数
			String orders=ordenos.replace(":", "','");
			workOrderService.updatePrintFormFlagByOrders("('"+orders+"')");
			
			json.put("status", "1");
			json.put("content", printerStyleTypes);
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
	}
	
	@RequestMapping(value = "ajaxPrintPackFormOrdenos", method = RequestMethod.POST)
	public void ajaxPrintPackFormOrdenos(
			@RequestParam(value = "ordenos") String ordenos,
			@RequestParam(value = "packformStyleId") Long packformStyleId,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			logger.info("ajaxPrintPackFormOrdenos打印的订单号:"+ordenos+"---随箱单ID:"+packformStyleId);
			json=new JSONObject();
			out=response.getWriter();
			
			//获取随箱单样式
			List<PrinterStyleType> printerStyleTypes=pickPrintUtil.printPackForm(ordenos, packformStyleId);
			
			//修改随箱单的打印状态 bug554 by zhangweize 2016-10-31 
			String[] ordernoStr = ordenos.split(":");
			List<String> ordernoList = Arrays.asList(ordernoStr);
			List<String> taskCodeList = workTaskService.findTaskCodeByOrders(ordernoList);
			workTaskService.updatePackFormStatus(taskCodeList);
			
			//修改打印次数
			String orders=ordenos.replace(":", "','");
			workOrderService.updatePrintFormFlagByOrders("('"+orders+"')");
			
			
			json.put("status", "1");
			json.put("content", printerStyleTypes);
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
	}
	/**
	 * 保修单打印
	 * @param workNos
	 * @param number
	 * @param ordeno
	 * @param response
	 */
	@RequestMapping(value = "ajaxPrintGuarantee", method = RequestMethod.POST)
	public void ajaxPrintGuarantee(
			@RequestParam(value = "taskCode") String taskCode,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
				json=new JSONObject();
				out=response.getWriter();
				List<WorkOrder> workOrder = workOrderService.findByTaskCodes(taskCode);
				//List<EdiOrder> ediOrder = workOrderService.findByTaskCodes(taskCode);
				json.put("workOrders", workOrder);
			//	json.put("ediOrders",ediOrder);
				json.put("status","1");
				out.print(json.toString());
		} catch (Exception e) {
			
			logger.error("打印加载错误", e);
		}
	}
	
	/**
	 * 重新保修单打印
	 * @param workNos
	 * @param number
	 * @param ordeno
	 * @param response
	 */
	@RequestMapping(value = "ajaxPrintguaranteeOrdenos", method = RequestMethod.POST)
	public void ajaxPrintguaranteeOrdenos(
			@RequestParam(value = "ordenos") String ordenos,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
				json=new JSONObject();
				out=response.getWriter();
				List<WorkOrder> workOrder = workOrderService.findByordenos(ordenos);
				json.put("workOrders",workOrder);
				json.put("status","1");
				out.print(json.toString());
		} catch (Exception e) {
			
			logger.error("打印加载错误", e);
		}
	}

	
	/**
	 * 根据订单号打印快递单信息（挑选重新打印）
	 * @param ordenos
	 * @param firstExpress
	 * @param expressId
	 * @param response
	 */
	@RequestMapping(value = "ajaxPrintPackExpressOrdenos", method = RequestMethod.POST)
	public void ajaxPrintPackExpress(
			@RequestParam(value = "ordenos") String ordenos,
			@RequestParam(value = "firstExpress") String firstExpress,
			@RequestParam(value = "expressId") Long expressId,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		ExpressStyle expressStyle=null;//KK
		try {
			logger.info("ordenos="+ordenos);
			logger.info("firstExpress="+firstExpress);
			logger.info("expressId="+expressId);
			json=new JSONObject();
			out=response.getWriter();
			List<PrinterStyleType> printerStyleTypes=pickPrintUtil.printExpress(ordenos, firstExpress,expressId);
			for(PrinterStyleType pst:printerStyleTypes){
				pst.setCustomerCode(workOrderDao.loadByOrderno(pst.getOrdeno()).getCustomerCode());
			}
			expressStyle=expressStyleService.findOne(expressId);//KK
			String[] remarks = getParams(expressStyle.getRemarks());//KK
			json.put("width", remarks[0]);//KK
			json.put("height", remarks[1]);//KK
			json.put("status", "1");
			json.put("content", printerStyleTypes);
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
	}
	
	/**
	 *根据任务编号，按指定的长度分割订单号
	 * @param taskCode
	 * @param size
	 * @param response
	 */
	@RequestMapping(value = "spliteEbillOrder", method = RequestMethod.POST)
	public void spliteEbillOrder(
			@RequestParam(value = "taskCode") String taskCode,
			@RequestParam(value = "size") int size,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			logger.info("开始分割订单号");
			logger.info("taskCode===" + taskCode + "\tsize=" + size);
			json = new JSONObject();
			out = response.getWriter();
			String content = pickPrintUtil.spliteEbillOrder(taskCode, size);
			json.put("status", "1");
			json.put("content", content);
			logger.info("content==="+content);
			out.print(json.toString());
		} catch (Exception e) {

			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
		logger.info(json.toString());
	}

	/**
	 * 根据订单号打印电子面单信息（挑选重新打印）
	 *
	 * @param ordenos 订单号集合
	 * @param expressId 快递模板ID
	 * @param taskCode 任务号
	 * @param response HttpServletResponse
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "ajaxPrintEBillExpress", method = RequestMethod.POST)
	public void ajaxPrintEBillExpress(@RequestParam(value = "ordenos") String ordenos, @RequestParam(value = "expressId") Long expressId,
									  @RequestParam(value = "taskCode") String taskCode, HttpServletResponse response) {

		PrintWriter out = null;
		JSONObject json = null;
		boolean isLockSuccess = false;

		try {
			json = new JSONObject();
			out = response.getWriter();

			isLockSuccess = workTaskService.lock("ajaxPrintEBillExpress", taskCode + "", "-");
			if (!isLockSuccess) {
				json.put("status", "0");
				json.put("content", "当前任务已在处理,请勿重复处理！");
				return;
			}

			Map<String, Object> map = printStyleService.getPrintStyleTypes(ordenos, expressId, taskCode);
			ExpressStyle expressStyle = (ExpressStyle) map.get("expressStyle");
			List<PrinterStyleType> printerStyleTypes = (List<PrinterStyleType>) map.get("printerStyleTypeList");

			String[] remarks = getParams(expressStyle.getRemarks());
			json.put("width",  remarks[0]);
			json.put("height",  remarks[1]);
			json.put("expressStyle", expressStyle);
			json.put("status", "1");
			json.put("content", printerStyleTypes);
			json.put("openCaiNiao", expressStyle.getCainiaoFlg());

		} catch (Exception e) {

			json.put("status", "0");
			json.put("content", e.getMessage());

			logger.error("{}打印电子面单错误:", taskCode, e);
		} finally {

			if (isLockSuccess) {
				workTaskService.releaseLock("ajaxPrintEBillExpress", taskCode + "");
			}
			out.print(json.toString());
		}
	}

	private String[] getParams(String content) {
		return content.split("\\*");
	}
	
	/**
	 * 快递单ajaxQueue分页打印
	 * @param workIds 流水批次号
	 * @param number  每次打印的数量
	 * @param firstExpress 起始快递单号
	 * @param expressID  快递单模版
	 * @param response
	 */
	@RequestMapping(value = "ajaxExpressCount", method = RequestMethod.POST)
	public void ajaxExpressCount(
			@RequestParam(value = "workIds") String workIds,
			@RequestParam(value = "number") int number,
			@RequestParam(value = "firstExpress") String firstExpress,
			@RequestParam(value = "expressID") Long expressID,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			logger.info("开始快递单的AJAX分页显示打印");
			logger.info("workIds==="+workIds+"\tnumber="+number+"\tfirstExpress="+firstExpress+"\texpressID="+expressID);
			json=new JSONObject();
			out=response.getWriter();
			String content=pickPrintUtil.expressCount(workIds, number,firstExpress,expressID);
			json.put("status", "1");
			json.put("content", content);
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
	}
	
	
	@RequestMapping(value = "ajaxPrintQueueExpress", method = RequestMethod.POST)
	public void ajaxPrintQueueExpress(
			@RequestParam(value = "queues") String queues,
			@RequestParam(value = "expressId") Long expressId,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		ExpressStyle expressStyle=null;//KK
		try {
			logger.info("使用ajaxQueue队列打印快递单");
			logger.info("queues="+queues);
			logger.info("expressId="+expressId);
			json=new JSONObject();
			out=response.getWriter();
			List<PrinterStyleType> printerStyleTypes=pickPrintUtil.printExpress(queues,expressId);
			
			expressStyle=expressStyleService.findOne(expressId);//KK
			String[] remarks = getParams(expressStyle.getRemarks());//KK
			if(queues.endsWith("finish")){
				json.put("index", "finish");
			}else{
				json.put("index", "pending");
			}
			json.put("width", remarks[0]);//KK
			json.put("height", remarks[1]);//KK
			json.put("status", "1");
			json.put("content", printerStyleTypes);
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
	}
	
	/**
	 * 根据流水批次打印快递单号打印（批次打印）
	 * 
	 * @param workNos
	 * @param number
	 * @param ordeno
	 * @param response
	 */
	@RequestMapping(value = "ajaxPrintPackExpress", method = RequestMethod.POST)
	public void ajaxPrintPackExpress(
			@RequestParam(value = "workId") Long workId,
			@RequestParam(value = "firstExpress",required=false) String firstExpress,
			@RequestParam(value = "expressId") Long expressId,
			@RequestParam(value = "printName") String printName,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		ExpressStyle expressStyle=null;//KK
		List<PrinterStyleType> printerStyleTypes=null;
		try {
			json=new JSONObject();
			out=response.getWriter();
			logger.info("根据流水号打印快递单");
			logger.info("workId==="+workId);
			logger.info("firstExpress==="+firstExpress);
			logger.info("expressId==="+expressId);
			logger.info("printName==="+printName);
			expressStyle=expressStyleService.findOne(expressId);
			logger.info("expressStyle.getType()==="+expressStyle.getType());
		
			printerStyleTypes=pickPrintUtil.printExpress(workId, firstExpress,expressId);
				
			String[] remarks = getParams(expressStyle.getRemarks());//KK
			json.put("width", remarks[0]);//KK
			json.put("height", remarks[1]);//KK
			json.put("status", "1");
			json.put("content", printerStyleTypes);
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
	}
	
	
	@RequestMapping(value = "ajaxPrintExpressOrdeno", method = RequestMethod.POST)
	public void ajaxPrintExpressOrdeno(
			@RequestParam(value = "ordeno") String ordeno,
			@RequestParam(value = "expressNo") String expressNo,
			@RequestParam(value = "companyCode") String companyCode,
			HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			json=new JSONObject();
			out=response.getWriter();
			logger.info("开始修改订单打印状态");
			logger.info("ordeno==="+ordeno);
			logger.info("expressNo==="+expressNo);
			logger.info("companyCode==="+companyCode);
			ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			User curUser=this.accountService.findUserByJobuuid(user.jobuuid);
			WMSPrinter printer=new WMSPrinter(ordeno,expressNo,companyCode,curUser);
			SynchroShippedBatchQueue.putWmsPrinterQueue(printer);
					
			json.put("status", "1");
			json.put("content", "修改成功");
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
		
	}
	
	/**
	 * 根据orderno获取taskCode
	 * @param orderno
	 * @param response
	 */
	@RequestMapping(value = "ajaxGetTaskCodeByOrderno", method = RequestMethod.POST)
	public void ajaxGetTaskCodeByOrderno(@RequestParam(value = "orderno") String orderno,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			json=new JSONObject();
			out=response.getWriter();
			String taskCode = workOrderDao.findByOrder(orderno).getTaskCode() ;
			
			json.put("status", "1");
			json.put("taskCode", taskCode);
			out.print(json.toString());
		} catch (Exception e) {
			
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("打印加载错误", e);
		}
		
	}
	/**
	 * 根据作业批次编号获取所有作业订单列表
	 * @param batchCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxGetWorkOrderByBatchCode", method = RequestMethod.POST)
	public void ajaxGetWorkOrderByBatchCode(@RequestParam(value = "batchCode") String batchCode,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			json=new JSONObject();
			out=response.getWriter();
			List<WorkOrder> workOrders = workOrderDao.loadOrderByBatchCode(batchCode);
			if(null!=workOrders){
				json.put("status", "1");
				json.put("workOrders", workOrders);
				//分配快递单号,随意获取一个expressId
				//获取订单快递对应的logistics_company表id字段
				String ordeno = workOrders.get(0).getOrder().getOrdeno() ;//获取订单号
				EdiOrder ediOrder = ediOrderService.findByOrdeno(ordeno) ;
				Long id = logisticsCompanyService.getLogisticsCompanyByCode(ediOrder.getCacode()).getId() ;//获取快递公司编码  TTKDEX  15
				List<ExpressStyle> expressStyles = expressStyleService.findByCustomerCodeAndAreaGroupCodeAndLogisticsCompanyId(workOrders.get(0).getCustomerCode(), workOrders.get(0).getWarehouseCode(),id) ;
				if(null == expressStyles||expressStyles.size()<1){
					json.put("status", "-2");
					json.put("content", "快递单模板未设置");
				}else{
					Long expressId = expressStyles.get(0).getId() ;
					String ordenos = "" ;
					for(int i=0;i<workOrders.size();i++){
						ordenos += workOrders.get(i).getOrder().getOrdeno()+":";
					}
					try{
						pickPrintUtil.printExpress(ordenos,expressId,workOrders.get(0).getTaskCode());
						//打印订单时设置已打印
						workOrderService.updateByBatchCode(batchCode);
					}catch(Exception e){
						logger.error("订单条码打印时分配运单号错误", e);
						json.put("status", "-1");
						json.put("content", "订单条码打印时分配运单号错误");
					}
				}
			}else{
				json.put("status", "0");
			}
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			logger.error("作业订单列表获取错误", e);
		}
	}
}